import { createSlice } from '@reduxjs/toolkit';

const initialState = {
    collectedQuestions: JSON.parse(localStorage.getItem('collectedQuestions')) || []
};

const collectSlice = createSlice({
    name: 'collect',
    initialState,
    reducers: {
        addCollectedQuestion: (state, action) => {
            // 检查是否已经收藏
            const exists = state.collectedQuestions.some(q => q._id === action.payload._id);
            if (!exists) {
                state.collectedQuestions.push(action.payload);
                // 保存到 localStorage
                localStorage.setItem('collectedQuestions', JSON.stringify(state.collectedQuestions));
            }
        },
        removeCollectedQuestion: (state, action) => {
            state.collectedQuestions = state.collectedQuestions.filter(q => q._id !== action.payload);
            // 更新 localStorage
            localStorage.setItem('collectedQuestions', JSON.stringify(state.collectedQuestions));
        }
    }
});

export const { addCollectedQuestion, removeCollectedQuestion } = collectSlice.actions;
export const selectCollectedQuestions = (state) => state.collect.collectedQuestions;
export default collectSlice.reducer; 